<?php
namespace api\utils;


/**
 * 微信公众号开发平台 api
 * @author yu
 */

class WeiXinApi
{

    //微信开发平台接入验证
    public function checkSignature($token)
    {

        // you must define TOKEN by yourself
        if ($token == '') {
            throw new Exception('TOKEN is not defined!');
        }

        $signature = $_GET["signature"];
        $timestamp = $_GET["timestamp"];
        $nonce = $_GET["nonce"];

        $tmpArr = array($token, $timestamp, $nonce);
        // use SORT_STRING rule
        sort($tmpArr, SORT_STRING);
        $tmpStr = implode($tmpArr);
        $tmpStr = sha1($tmpStr);

        if ($tmpStr == $signature) {
            return true;
        } else {
            return false;
        }
    }

    /**---------------------自定义菜单---------------------------**/
    /**
     * 获取菜单
     */
    public function getMenu($accesstoken)
    {
        $url = "https://api.weixin.qq.com/cgi-bin/menu/get?access_token=$accesstoken";
        $result = json_decode(file_get_contents($url), true);
        return $result;
    }

    /**
     * 创建菜单
     */
    public function creatMenu($token, $data)
    {
        $url = "https://api.weixin.qq.com/cgi-bin/menu/create?access_token=$token";
        $result = json_decode(weixinapi::https_request($url, $data), true);
        echo "start create menu";
        var_dump($result);

        if (isset($result['errcode']) && $result['errcode'] != 0) {
            echo "创建菜单出问题！" . $result->errcode . $result->errmsg;
            exit;
        }
        return $result;
    }

    /**
     * 删除菜单
     */
    public function delmenu($token)
    {
        $url = "https://api.weixin.qq.com/cgi-bin/menu/delete?access_token=$token";
        $result = json_decode(weixinapi::https_request($url), true);
        echo "start del menu";

        var_dump($result);
        if (isset($result['errcode']) && $result['errcode'] != 0) {
            echo "删除菜单出问题！" . $result->errcode . $result->errmsg;
            exit;
        }
        return $result;
    }


    /**---------------------微信授权登录---------------------------**/


    /**
     * 获取微信授权链接
     *
     * @param string $redirect_uri 跳转地址
     * @param mixed $state 参数
     */
    public function get_authorize_url($app_id = '', $redirect_uri = '', $state = '')
    {
        $redirect_uri = urlencode($redirect_uri);
        return "https://open.weixin.qq.com/connect/oauth2/authorize?appid={$app_id}&redirect_uri={$redirect_uri}&response_type=code&scope=snsapi_userinfo&state={$state}#wechat_redirect";
    }

    /**
     * 获取授权token
     *
     * @param string $code 通过get_authorize_url获取到的code
     */
    public function get_access_token($app_id = '', $app_secret = '', $code = '')
    {
        $token_url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid={$app_id}&secret={$app_secret}&code={$code}&grant_type=authorization_code";

        $result = json_decode(weixinapi::https_request($token_url), true);

        if (isset($result['access_token'])) {
            return $result;
        }

        return FALSE;
    }

    /**
     * 获取授权后的微信用户信息
     *
     * @param string $access_token
     * @param string $open_id
     */
    public function get_user_info($access_token = '', $open_id = '')
    {
        if ($access_token && $open_id) {
            $info_url = "https://api.weixin.qq.com/sns/userinfo?access_token={$access_token}&openid={$open_id}&lang=zh_CN";

            $result = json_decode(weixinapi::https_request($info_url), true);

            if (isset($result['openid'])) {
                return $result;
            }
        }

        return FALSE;
    }

    /**---------------------微信基本接入---------------------------**/

    public function getAccessToken($appid, $appser)
    {
        if (!$appid || !$appser) exit('配置出错，请检查！');
        $api = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=$appid&secret=$appser";
        $result = json_decode(file_get_contents($api));
        if (isset($result->errcode)) {
            echo '<h1>错误token：</h1>' . $result->errcode;
            echo '<br/><h2>错误信息token：</h2>' . $result->errmsg;
            exit;
        }
        return $result->access_token;
    }

    /**
     * 获取请求对象
     * @return null|\SimpleXMLElement
     */
    public function getRequestObj()
    {

        //get post data, May be due to the different environments
        //$postStr = $GLOBALS["HTTP_RAW_POST_DATA"];
        $postStr = file_get_contents("php://input");
        //extract post data
        if (!empty($postStr)) {
            /* libxml_disable_entity_loader is to prevent XML eXternal Entity Injection,
                the best way is to check the validity of xml by yourself */
            libxml_disable_entity_loader(true);
            $postObj = simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA);

            return $postObj;

        } else {
            return null;
        }
    }

    /**
     * 回复单条图文消息
     * @param $object
     * @param $title
     * @param $description
     * @param $picurl
     * @param $url
     * @return string
     */
    public function responseOneImageText($object, $title, $description, $picurl, $url)
    {

        $textTpl = "<xml>
                    <ToUserName><![CDATA[%s]]></ToUserName>
                    <FromUserName><![CDATA[%s]]></FromUserName>
                    <CreateTime>%s</CreateTime>
                    <MsgType><![CDATA[news]]></MsgType>
                    <ArticleCount>1</ArticleCount>
                    <Articles>
                    <item>
                    <Title><![CDATA[%s]]></Title>
                    <Description><![CDATA[%s]]></Description>
                    <PicUrl><![CDATA[%s]]></PicUrl>
                    <Url><![CDATA[%s]]></Url>
                    </item>
                    </Articles>
                    </xml>";

        $resultStr = sprintf($textTpl, $object->FromUserName, $object->ToUserName, time(), $title, $description, $picurl, $url);
        return $resultStr;
    }


    /**
     * 回复文本消息
     * @param $object
     * @param $content
     * @param int $flag
     * @return string
     */
    public function responseText($object, $content, $flag = 0)
    {
        $textTpl = "<xml>
                    <ToUserName><![CDATA[%s]]></ToUserName>
                    <FromUserName><![CDATA[%s]]></FromUserName>
                    <CreateTime>%s</CreateTime>
                    <MsgType><![CDATA[text]]></MsgType>
                    <Content><![CDATA[%s]]></Content>
                    <FuncFlag>%d</FuncFlag>
                    </xml>";
        $resultStr = sprintf($textTpl, $object->FromUserName, $object->ToUserName, time(), $content, $flag);
        return $resultStr;
    }

    public static function https_request($url, $data = null)
    {
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
        if (!empty($data)) {
            curl_setopt($curl, CURLOPT_POST, 1);
            curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
        }
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        $output = curl_exec($curl);
        curl_close($curl);
        return $output;
    }
}